<extend name="Common@Layout:layui" />
<block name="title">
    <title>聊天</title>
</block>
<block name="style">
<css href="/Public/res/css/layim.css?v=1" />
<style>
	body .layui-edit-face {
            border: none;
            background: none;
        }
        
        body .layui-edit-face .layui-layer-content {
            padding: 0;
            background-color: #fff;
            color: #666;
            box-shadow: none
        }
        
        .layui-edit-face .layui-layer-TipsG {
            display: none;
        }
        
        .layui-edit-face ul {
            position: relative;
            width: 372px;
            padding: 10px;
            border: 1px solid #D9D9D9;
            background-color: #fff;
            box-shadow: 0 0 20px rgba(0, 0, 0, .2);
        }
        
        .layui-edit-face ul li {
            cursor: pointer;
            float: left;
            border: 1px solid #e8e8e8;
            height: 22px;
            width: 26px;
            overflow: hidden;
            margin: -1px 0 0 -1px;
            padding: 4px 2px;
            text-align: center;
        }
        
        .layui-edit-face ul li:hover {
            position: relative;
            z-index: 2;
            border: 1px solid #eb7350;
            background: #fff9ec;
        }
        .dis{display: none !important;}
        #chat .layui-layer-title{height: 80px !important;}
        .layui-layim-list li{padding: 5px 50px 5px 60px !important;}
        .rongcloud-badge {
        	margin-top: 11px;
		    float: right;
		    background-color: #009688;
		    font-weight: normal;
		    min-width: 10px;
		    padding: 3px 5px;
		    line-height: 1;
		    color: #fff;
		    text-align: center;
		    white-space: nowrap;
		    vertical-align: baseline !important;
		    border-radius: 10px;
		}
		.fly-home{
			border: 1px dashed #ccc;
			text-align: center;
			z-index: 999999;
			position: fixed;
			left: 805px;
			background-color: white;
			padding: 0px 15px;
		}
		.fly-home img {
		    width: 120px;
		    height: 120px;
		    border-radius: 100%;
		}
		.fly-home h1 {
		    font-size: 26px;
		    line-height: 30px;
		    margin-top: 10px;
		}
		.lxd-img{cursor: pointer;}
		.delete-user {
			display: inline-block;
			z-index: 888;
		    position: absolute;
		    top: 16px;
		    right: 11px;
		    font-size: 20px;
		    width: 20px;
		    height: 20px;
		    background: url(/Public/img/chacha.png) no-repeat;
		}
</style>
</block>

<block name="main">
    <input type="hidden" id="myuid" value="{$_SESSION['loginUser']['uid']}">
    <input type="hidden" id="myname" value="{$_SESSION['loginUser']['username']}">
    <input type="hidden" id="myavatar" value="{$_SESSION['loginUser']['avater'] | default='/Public/res/images/avatar/default.png'}">
	
	<!--信息提示音-->
	<audio  id="song" src="" autoplay="autoplay"></audio>
	
	<!--搜索框-->
	<div id="search" class="layui-form">
		<div class="layui-inline" style="position: fixed;width: 200px; height: 38px; bottom: 600px; left: 0px;background-color: white;z-index: 9999;">
	        <select id="keyword" lay-verify="required" lay-search="">
				<option value="">搜索最近联系人</option>
				<volist name="users" id="vo">
                    <option value="{$vo.username}">{$vo.username}</option>
                </volist>
	        </select>
      	</div>
		<!--<input type="text" name="keyword" value="" id="keyword" placeholder="搜索联系人" style="position: fixed;width: 200px; height: 40px; bottom: 600px; left: 0px;background-color: white;" class="layui-input">-->
		<a href="javascript:;" id="search_click" class="layui-btn" style="position: fixed;width: 50px; height: 38px; bottom: 600px; left: 200px;border-radius: 0px;z-index: 9999;">
			<i class="layui-icon"></i>
		</a>
	</div>
	
    <div id="test" class="dis" style="position: fixed;width: 150px; height: 50px; bottom: 0px; left: 0px;box-shadow:1px 1px 50px rgba(0,0,0,.3);">
        <div id="fukuang" style="line-height:50px;text-align:center;cursor:pointer"><span><i class="layui-icon"></i>最近联系人</span></div>
    </div>
    <div id="friendList" style="position: fixed;width: 250px; height: 600px; bottom: 0px; left: 0px;box-shadow:1px 0px 10px rgba(0,0,0,.3);">
    	<div class="layui-layer-title" style="height: 40px !important;">
    		<i class="layui-icon"></i>
    		&nbsp;&nbsp;最近联系人
    	</div>
    	<span class="layui-layer-setwin" id="friendList_close">
    		<i class="layui-icon" style="cursor: pointer;" ></i>
    	</span>
    		
        <div class="layui-layim-main" style="top:0;">
            <ul class="layui-layim-list  layui-show">
            	<!--<if condition="$users">
                <volist name="users" id="vo">
                    <li class="openDialog user_{$vo.uid}" data-title="{$vo.title}" data-tid="{$vo.uid}" data-username="{$vo.username}" data-avatar="<if condition='vo.avater'>{$vo.avater}<else/>'/Public/res/images/avatar/default.png'</if>">
                        <img src="<if condition='vo.avater'>{$vo.avater}<else/>'/Public/res/images/avatar/default.png'</if>">
                        <span>{$vo.username}</span>
                        <i class="rongcloud-badge dis">0</i>
                    </li>
                </volist>
                <else/>
                	<div class="no_user" style="text-align: center;margin-top: 20px;">暂无联系人</div>
                </if>-->
                <div class="no_user" style="text-align: center;margin-top: 20px;">暂无联系人</div>
            </ul>
        </div>
    </div>
    
    <!--聊天窗口-->
    <div id="chat" class="dis" style="width: 550px;height: 600px;position: absolute;left: 255px;bottom: 0; box-shadow:1px 1px 50px rgba(0,0,0,.3);background-color: white;"> 
    	<!--标题-->
    	<div class="layui-layer-title">
    		<div class="layim-chat-other">
    			<img class="touser_avater" src="/Public/res/images/avatar/default.png">
    			<span class="layim-chat-username touser_username" layim-event=""></span>
    			<p class="layim-chat-status"></p>
    		</div>
    	</div>
    	<!--关闭窗口按钮-->
    	<span class="layui-layer-setwin">
    		<a class="layui-layer-ico layui-layer-close layui-layer-close1" href="javascript:;" id="chat_close"></a>
    	</span>
    	<!--聊天内容-->
	    <div class="layim-chat-main" style="height: 340px;">
	    	<div class="layim-chat-system look_more dis"><span layim-event="chatLog">查看更多记录</span></div>
	        <ul></ul>
	    </div>
	    <!--底部功能-->
	    <div class="layim-chat-footer">
	        <div class="layui-unselect layim-chat-tool">
	            <span class="layui-icon layim-tool-face" title="选择表情" layim-event="face"></span>
	            <span class="layui-icon layim-tool-image" title="上传图片" layim-event="image">
	            	<input required="" type="file" name="file" class="layui-upload-file" value="" >
	            </span>
	            <span class="layim-tool-log" layim-event="chatLog"><i class="layui-icon"></i>聊天记录</span>
	        </div>
	        <div class="layim-chat-textarea"><textarea></textarea></div>
	        <div class="layim-chat-bottom">
	            <div class="layim-chat-send">
	                <span class="layim-send-close" layim-event="send">发送</span>
	            </div>
	        </div>
	    </div>
    </div>
    
	<!--教师信息-->
	<div class="fly-home dis">  
		<img class="touser_avater" src="//q.qlogo.cn/qqapp/101235792/E41571F407EF2DC10CE0855EB3566F1C/100" alt="56教室客服">  
		<h1 class="touser_username"></h1> 
		<h1 class="touser_school"></h1>  
	</div>
	
    <script id="data-tpl" type="text/html">
        {{# layui.each(d, function(index, item){ }}
        <li {{# if(item.ismine==1 ) { }}class="layim-chat-mine" {{# } }}>
            <div class="layim-chat-user">
                <img src="{{item.user.portraitUri}}"> {{# if(item.ismine==1 ) { }}
                <cite><i>{{item.mtime}}</i>{{item.user.name}}</cite> {{# } }} {{# if(item.ismine==0 ) { }}
                <cite>{{item.user.name}}<i>{{item.mtime}}</i></cite> {{# } }}
            </div>
            <div class="layim-chat-text">{{item.content}}</div>
        </li>
        {{# }); }}
    </script>
    
</block>

<block name="script">
    <js href="http://cdn.ronghub.com/RongIMLib-2.2.5.min.js" />
    <script>
        layui.use(['jquery', 'layer', 'form', 'face', 'laytpl','upload'], function() {
            var $ = layui.jquery,
                faces = layui.face,
                layer = layui.layer,
                laytpl = layui.laytpl,
                form = layui.form();
            
            var height = document.body.scrollHeight;

			//聊天对象
			var touser = {};
			var is_open = 0;
            var p = 1;
            var row = 10;
            var totalCount = 0;
            var domHeight = 0;
            
			$('.fly-home').css('top',document.body.scrollHeight-600)
			
			layui.upload({
	            url: '/content/image/qiniu_upload?type=image',
	            elem: '.layui-upload-file',
	            unwrap: true,
	            before: function() {
	                ii = layer.msg('图片上传中，请稍等...', {
	                    icon: 16,
	                    time: 10000
	                });
	            },
	            success: function(res) {
	                if (res.status) {
	                    $('.layim-chat-textarea textarea').val($('.layim-chat-textarea textarea').val() + 'img[' + res.data.url + ']');
	                    $('.layim-chat-textarea textarea').focus();
	                    layer.close(ii);
	                } else {
	                    layer.msg(res.info, { icon: 5 });
	                }
	            }
	        });
	        
			function listen_img_fangda(){
				$('.lxd-img').unbind('click').click(function(){
					layer.photos({
		                photos: '.layim-chat-text',
		                anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
		            });
				});
			}

			
			//显示聊天窗口
			listen_click();
			//监听用户列表点击事件
			function listen_click(){
				$('.openDialog').unbind('click').click(function() {
	            	p = 1;
	            	totalCount = 0;
	                var $this = $(this);
	                touser.id = $this.attr('data-tid');
	                touser.title = $this.attr('data-title');
	                touser.username = $this.attr('data-username');
	                touser.avater = $this.attr('data-avatar');
	            	get_message();
	                
	                $('.touser_avater').attr('src',touser.avater);
	                $('.touser_username').text(touser.username);
	                $('.touser_school').text(touser.title);
	                $('.user_'+touser.id+' .rongcloud-badge').html('0');
	                $('.user_'+touser.id+' .rongcloud-badge').addClass('dis');
	            	is_open = 1;
	            	$('.layim-chat-main').css('height', '340px');
	            	$('#chat').removeClass('dis');
	            	$('.fly-home').removeClass('dis');
	            });
	            
	            $('.delete-user').unbind('click').click(function(){
	            	$this = $(this);
	            	var asker = layer.confirm('是否删除该用户',function(){
	            		$this.parent().remove();
		            	if($('.layui-layim-list li').length == 0){
		            		$('.no_user').removeClass('dis');
		            	}
		            	$('#chat').addClass('dis');
		            	$('.fly-home').addClass('dis');
						layer.close(asker);
	            	});
	            	event.stopPropagation();
	            	
				});
			}
            
			//显示列表
			$('#test').click(function(){
        		$('#test').addClass('dis');
        		$('#friendList').removeClass('dis');
        		$('#search').removeClass('dis');
        		if(is_open == 1){
        			$('#chat').removeClass('dis');
        			$('.fly-home').removeClass('dis');
        		}
			});
			//隐藏列表
			$('#friendList_close').click(function(){
        		$('#friendList').addClass('dis');
        		$('#search').addClass('dis');
        		$('#chat').addClass('dis');
        		$('.fly-home').addClass('dis');
        		$('#test').removeClass('dis');
			});
			
			//窗口关闭---隐藏
			$('#chat_close').click(function(){
            	is_open = 0;
        		$('#chat').addClass('dis');
        		$('.fly-home').addClass('dis');
			});

            var isConnected = false;
            
            var myinfo = {
                id: $('#myuid').val(),
                name: $('#myname').val(),
                portraitUri: $('#myavatar').val()
            };
		
			
            $.get('/plugin/rongcloud/get_token', function(ret) {
                if (ret.status) {
                    initRongCloud(ret.data.ak, ret.data.token);
                } else {
                    layer.alert(ret.info);
                }
            });

            function initRongCloud(ak, token) {
                RongIMClient.init(ak);

                // 设置连接监听状态 （ status 标识当前连接状态）
                // 连接状态监听器
                RongIMClient.setConnectionStatusListener({
                    onChanged: function(status) {
                        switch (status) {
                            //链接成功
                            case RongIMLib.ConnectionStatus.CONNECTED:
                                console.log('链接成功');
                                break;
                                //正在链接
                            case RongIMLib.ConnectionStatus.CONNECTING:
                                console.log('正在链接');
                                break;
                                //重新链接
                            case RongIMLib.ConnectionStatus.DISCONNECTED:
                                console.log('断开连接');
                                break;
                                //其他设备登录
                            case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
                                console.log('其他设备登录');
                                break;
                                //网络不可用
                            case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
                                console.log('网络不可用');
                                break;
                        }
                    }
                });

                // 消息监听器
                RongIMClient.setOnReceiveMessageListener({
                    // 接收到的消息
                    onReceived: function(message) {
                    	if(window.Notification && Notification.permission !== "denied") {
					        Notification.requestPermission(function(status) {    // 请求权限
					            if(status === 'granted') {
					                // 弹出一个通知
					                var n = new Notification('消息', {
					                    body : message.content.user.name+' 发来一条聊天信息',
					                    icon : '/Public/img/notice.png'
					                });
					                // 关闭通知
//					                setTimeout(function() {
//					                    n.close();
//					                }, 5000);
					            }
					        });
					    }
                    	//播放信息提示音
                        $('#song').attr('src','/Public/mp3/sms-received.mp3');
                        console.log(message);
                        if(!$('.user_'+message.content.user.id).length > 0){
                        	var html = '<li class="openDialog user_'+message.content.user.id+'" data-title="'+message.content.user.school+'" data-tid="'+message.content.user.id+'" data-username="'+message.content.user.name+'" data-avatar="'+message.content.user.portraitUri+'">'+
					                        '<img src="'+message.content.user.portraitUri+'">'+
					                        '<span>'+message.content.user.name+'</span>'+
					                        '<i class="rongcloud-badge">0</i>'+
					                        '<i class="delete-user"></i>'+
					                    '</li>';
                        	$('#friendList ul').prepend(html);
                        	$('.no_user').addClass('dis');
                        	listen_click();
                        }
                        
                        // 判断消息类型
                        switch (message.messageType) {
                            case RongIMClient.MessageType.TextMessage:
                                // 发送的消息内容将会被打印
                                if(is_open && message.content.user.id==touser.id){
                                	show_item_msg(0, message.content.user, message.content.content, message.receivedTime);
                                }else{
                                	var t = $('.user_'+message.content.user.id+' .rongcloud-badge').html();
                                	$('.user_'+message.content.user.id+' .rongcloud-badge').removeClass('dis');
                                	$('.user_'+message.content.user.id+' .rongcloud-badge').html(parseInt(t)+1);
                                }
                                break;
                            case RongIMClient.MessageType.VoiceMessage:
                                // 对声音进行预加载                
                                // message.content.content 格式为 AMR 格式的 base64 码
                                RongIMLib.RongIMVoice.preLoaded(message.content.content);
                                break;
                            case RongIMClient.MessageType.ImageMessage:
                                // do something...
                                break;
                            case RongIMClient.MessageType.DiscussionNotificationMessage:
                                // do something...
                                break;
                            case RongIMClient.MessageType.LocationMessage:
                                // do something...
                                break;
                            case RongIMClient.MessageType.RichContentMessage:
                                // do something...
                                break;
                            case RongIMClient.MessageType.DiscussionNotificationMessage:
                                // do something...
                                break;
                            case RongIMClient.MessageType.InformationNotificationMessage:
                                // do something...
                                break;
                            case RongIMClient.MessageType.ContactNotificationMessage:
                                // do something...
                                break;
                            case RongIMClient.MessageType.ProfileNotificationMessage:
                                // do something...
                                break;
                            case RongIMClient.MessageType.CommandNotificationMessage:
                                // do something...
                                break;
                            case RongIMClient.MessageType.CommandMessage:
                                // do something...
                                break;
                            case RongIMClient.MessageType.UnknownMessage:
                                // do something...
                                break;
                            default:
                                // 自定义消息
                                // do something...
                        }
                    }
                });

                // 连接融云服务器。
                RongIMClient.connect(token, {
                    onSuccess: function(userId) {
                        console.log("Login successfully." + userId);
                        isConnected = true;
                    },
                    onTokenIncorrect: function() {
                        console.log('token无效');
                    },
                    onError: function(errorCode) {
                        var info = '';
                        switch (errorCode) {
                            case RongIMLib.ErrorCode.TIMEOUT:
                                info = '超时';
                                break;
                            case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                                info = '未知错误';
                                break;
                            case RongIMLib.ErrorCode.UNACCEPTABLE_PaROTOCOL_VERSION:
                                info = '不可接受的协议版本';
                                break;
                            case RongIMLib.ErrorCode.IDENTIFIER_REJECTED:
                                info = 'appkey不正确';
                                break;
                            case RongIMLib.ErrorCode.SERVER_UNAVAILABLE:
                                info = '服务器不可用';
                                break;
                        }
                        console.log(errorCode);
                    }
                });
            }
			
			//聊天窗口模块
			function show_face() {
                var str = '',
                    ul;
                for (var key in faces) {
                    str += '<li title="' + key + '"><img src="' + faces[key] + '"></li>';
                }
                str = '<ul id="LAY-editface" class="layui-clear">' + str + '</ul>';

                layer.tips(str, $('.layim-chat-footer'), {
                    tips: 1,
                    time: 0,
                    skin: 'layui-edit-face'
                });


                $('#LAY-editface li').on('click', function() {
                    var title = $(this).attr('title') + ' ';
                    $('.layim-chat-textarea textarea').val($('.layim-chat-textarea textarea').val() + 'face' + title);
                    $('.layim-chat-textarea textarea').focus();

                });
            }
            $('.layim-chat-textarea textarea').focus(function() {
                layer.closeAll('tips');
            });

            $('.layim-chat-textarea textarea').keyup(function(e) {

                if (e.keyCode == 13) {
                    sendMsg();
                    return false;
                }

            });

            $('.layim-chat-footer span').unbind('click').click(function() {
                var $this = $(this);
                if ($this.attr('layim-event') == 'face') {
                    show_face();
                }

                if ($this.attr('layim-event') == 'send') {
                    sendMsg();
                }
            });
			
			$('.look_more').click(function(){
				p++;
				get_message();
			});
			
			$('.layim-tool-log').click(function(){
				layer.open({
                    type: 2,
                    title: '聊天记录',
                    shade: [0],
                    shadeClose: true,
                    area: ['450px', '100%'],
                    offset: 'rb', //右下角弹出
                    anim: 2,
                    content: '/Plugin/Rongcloud/chatlog/tid/'+touser.id,
                });
			});
			
			function get_message(){
				$.post('/Plugin/Chat/get_message',{"uid":myinfo.id,"touid":touser.id,"p":p,"row":row},function(ret){
					
					var $dataDom = $('.layim-chat-main ul');
	                var dataTpl = $('#data-tpl').html();
	                if(ret.status){
			            var datas = [];
	                	var data = ret.data.data;
	                	totalCount += data.length;
	                	var total = ret.data.total;
	                	if(totalCount != total){
	                		$('.layim-chat-system').removeClass('dis');
	                	}else{
	                		$('.layim-chat-system').addClass('dis');
	                	}
	                	for(var i=data.length-1; i>=0; i--){
	                		var ismine = 0;
	                		var user = {};
	                		if(data[i].uid == myinfo.id){
	                			ismine = 1;
	                		}
	                		user.name = data[i].username;
	                		user.portraitUri = data[i].avater?data[i].avater:'/Public/res/images/avatar/default.png';
	                		var dataSingle = {
			                    'ismine': ismine,
			                    'user': user,
			                    'mtime': data[i].send_time,
			                    'content': changeContent(data[i].content)
			                };
			                datas.push(dataSingle);
	                	}
	                	laytpl(dataTpl).render(datas, function(html) {
	                		if(p == 1){
	                			$dataDom.html(html);
			                    $('.layim-chat-main').scrollTop($dataDom.height());
			                    domHeight = $dataDom.height();
	                		}else{
	                			$dataDom.prepend(html);
	                			$('.layim-chat-main').scrollTop($dataDom.height() - domHeight);
			                    domHeight = $dataDom.height();
	                		} 
	                		listen_img_fangda();
		                });
	                }
	                
				});
			}
			
			function save_message(touid,content,time){
				//touid-消息接收者UID  content-发送消息内容   uid-消息发送者者UID
				$.post('/Plugin/Chat/save_message',{"touid":touid,"content":content,"uid":myinfo.id,"send_time":time},function(){
					
				});
			}
			
			$('#search_click').click(function(){
				var keyword = $('#keyword').val();
				if(keyword.length>0){
					$.post('/Plugin/Chat/search_user',{"keyword":keyword},function(ret){
						if(ret.status){
							layer.msg(ret.info,{icon:1,time:1000});
							var data = ret.data[0];	                		
							var avaters = data.avater?data.avater:'/Public/res/images/avatar/default.png';
							if(!$('.user_'+data.uid).length > 0){
	                        	var html = '<li class="openDialog user_'+data.uid+'" data-title="'+data.title+'" data-tid="'+data.uid+'" data-username="'+data.username+'" data-avatar="'+avaters+'">'+
						                        '<img src="'+avaters+'">'+
						                        '<span>'+data.username+'</span>'+
						                        '<i class="rongcloud-badge dis">0</i>'+
						                        '<i class="delete-user"></i>'+
						                    '</li>';
	                        	$('#friendList ul').prepend(html);
	                        	$('.no_user').addClass('dis');
	                        	listen_click();
	                        }
						}else{
							layer.msg(ret.info,{icon:2,time:1000});
						}
					});
				}
			});
			
            function sendMsg() {
                if (isConnected) {
                    var cnt = $('.layim-chat-textarea textarea').val();
                    if (cnt == "") {
                        layer.alert('消息不能为空');
                        return false;
                    }

                    $('.layim-chat-textarea textarea').val("");


                    // 定义消息类型,文字消息使用 RongIMLib.TextMessage
                    var msg = new RongIMLib.TextMessage({
                        content: cnt,
                        user: myinfo,
                        extra: ''
                    });
                    //或者使用RongIMLib.TextMessage.obtain 方法.具体使用请参见文档
                    //var msg = RongIMLib.TextMessage.obtain("hello");

                    var conversationtype = RongIMLib.ConversationType.PRIVATE; // PRIVATE 为单聊、DISCUSSION 为讨论组、GROUP 为群组、CHATROOM 为聊天室、CUSTOMER_SERVICE 为客服、SYSTEM 为系统消息、APP_PUBLIC_SERVICE 为应用公众账号（应用内私有）、PUBLIC_SERVICE 为公众账号 (公有)
                    
                    RongIMClient.getInstance().sendMessage(conversationtype, touser.id, msg, {
                        // 发送消息成功
                        onSuccess: function(message) {
                            //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
                            console.log("Send successfully");
                            //保存聊天内容
                            save_message(message.targetId,message.content.content,formatDateTime(message.sentTime));
                            
                            show_item_msg(1, myinfo, cnt, Date.parse(new Date()));
                        },
                        onError: function(errorCode, message) {
                            var info = '';
                            switch (errorCode) {
                                case RongIMLib.ErrorCode.TIMEOUT:
                                    info = '超时';
                                    break;
                                case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                                    info = '未知错误';
                                    break;
                                case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                                    info = '在黑名单中，无法向对方发送消息';
                                    break;
                                case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                                    info = '不在讨论组中';
                                    break;
                                case RongIMLib.ErrorCode.NOT_IN_GROUP:
                                    info = '不在群组中';
                                    break;
                                case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                                    info = '不在聊天室中';
                                    break;
                                default:
                                    info = x;
                                    break;
                            }
                            console.log('发送失败:' + info);
                        }
                    });
                } else {
                    layer.alert("尚未连接服务器");
                }

            }

            function show_item_msg(ismine, user, content, mtime) {
                var $dataDom = $('.layim-chat-main ul');
                var dataTpl = $('#data-tpl').html();
                var dataSingle = {
                    'ismine': ismine,
                    'user': user,
                    'mtime': formatDateTime(mtime),
                    'content': changeContent(content)
                };
                var data = [];
                data[0] = dataSingle;
                laytpl(dataTpl).render(data, function(html) {
                    $dataDom.append(html);

                    $('.layim-chat-main').scrollTop($dataDom.height());
            		listen_img_fangda();
                });
            }


            function changeContent(content) {
                //支持的html标签
                var html = function(end) {
                    return new RegExp('\\[' + (end || '') + '(pre|div|table|thead|th|tbody|tr|td|ul|li|ol|li|dl|dt|dd|h2|h3|h4|h5)\\]\\n*', 'g');
                };
                content = escape(content || '') //XSS
                    .replace(/img\[([^\s]+?)\]/g, function(img) { //转义图片
                        return '<img data-isbig="0" class="lxd-img" src="' + img.replace(/(^img\[)|(\]$)/g, '') + '">';
                    }).replace(/@(\S+)(\s+?|$)/g, '@<a href="javascript:;" class="fly-aite">$1</a>$2') //转义@
                    .replace(/face\[([^\s\[\]]+?)\]/g, function(face) { //转义表情
                        var alt = face.replace(/^face/g, '');
                        return '<img alt="' + alt + '" title="' + alt + '" src="' + faces[alt] + '">';
                    }).replace(/a\([\s\S]+?\)\[[\s\S]*?\]/g, function(str) { //转义链接
                        var href = (str.match(/a\(([\s\S]+?)\)\[/) || [])[1];
                        var text = (str.match(/\)\[([\s\S]*?)\]/) || [])[1];
                        if (!href) return str;
                        var rel = /^(http(s)*:\/\/)\b(?!(\w+\.)*(sentsin.com|layui.com))\b/.test(href.replace(/\s/g, ''));
                        return '<a href="' + href + '" target="_blank"' + (rel ? ' rel="nofollow"' : '') + '>' + (text || href) + '</a>';
                    }).replace(html(), '\<$1\>').replace(html('/'), '\</$1\>') //转移代码
                    .replace(/\n/g, '<br>') //转义换行   
                return content;
            }

            function escape(html) {
                return String(html || '').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
                    .replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;');
            }
            
            function formatDateTime(inputTime) {
                var date = new Date(inputTime);
                var y = date.getFullYear();
                var m = date.getMonth() + 1;
                m = m < 10 ? ('0' + m) : m;
                var d = date.getDate();
                d = d < 10 ? ('0' + d) : d;
                var h = date.getHours();
                h = h < 10 ? ('0' + h) : h;
                var minute = date.getMinutes();
                var second = date.getSeconds();
                minute = minute < 10 ? ('0' + minute) : minute;
                second = second < 10 ? ('0' + second) : second;
                return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
            };
			
        });
    </script>
</block>